<?php

namespace App\Store\Controllers\Wxapp\WxappGift;

use App\Common\Services\Store\Common as StoreCommon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Wxapp\Gift\WxappGiftAllot;
use App\Store\Models\Wxapp\Gift\WxappGiftCategory;
use App\Store\Models\Wxapp\Gift\WxappGiftLog;
use App\Store\Models\Wxapp\Gift\WxappGiftStocklist as WxappGiftStock;
use App\Store\Validate\Wxapp\WxappGift\WxappGiftStock as ValidateWxappGiftStock;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use PhpOffice\PhpSpreadsheet\Shared\Date;
/**
 * 礼品库存
 */
class WxappGiftStockController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = WxappGiftStock::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = WxappGiftStock::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }
    /**
     * 新增
     */
    public function dopostadd(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $req_data = $request->only(['gift_category_id','gift_name','price','total_count','need_points','piecelimit','valid_type','valid_num','valid_end_at','gift_img','desc']);
        $Validate = new ValidateWxappGiftStock();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        if($req_data['valid_type']==1 || $req_data['valid_type']==7){
            if($req_data['valid_type']==7){
                if(!isset($req_data['valid_end_at']) || strtotime($req_data['valid_end_at'])<=0){
                    return response()->json(['code' => '001', 'msg' => '截至有效期必须为时间格式']);
                }
                $req_data['valid_end_at']=strtotime($req_data['valid_end_at']);
            }else{
                $req_data['valid_end_at']=0;

            }
            $req_data['valid_num']=0;
        }else{
            //有效期类型，1永久，2年，3季度，4月，5周，6天，7指定时间
            if(!isset($req_data['valid_num']) || $req_data['valid_num']<=0){
                return response()->json(['code' => '001', 'msg' => '请输入有效期数']);
            }else{
                if($req_data['valid_type']==2){
                    $req_data['valid_end_at']=strtotime('+'.$req_data['valid_num'].' year');
                }elseif($req_data['valid_type']==3){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']*3).' month');
                }elseif($req_data['valid_type']==4){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']).' month');
                }elseif($req_data['valid_type']==5){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']*7).' day');
                }elseif($req_data['valid_type']==6){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']).' day');
                }
            }
        }

        $data=$req_data;
        $data['desc']=isset($data['desc'])?$data['desc']:'';
        $data['cp_id']=$cp_id;
        $data['current_count']=$data['total_count'];
        $data['create_account_id']=$accountinfo['id'];
        $data['create_account_real_name']=$accountinfo['real_name'];
        $data['update_account_id']=$accountinfo['id'];
        $data['update_account_real_name']=$accountinfo['real_name'];
        $data['create_at']=time();
        $data['update_at']=time();
        $data['audit_status']=1;
        WxappGiftStock::create($data);
        return response()->json(['code'=>'000','msg'=>'新增成功']);
    }
    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $req_data = $request->only(['id','gift_category_id','gift_name','price','total_count',
        // 'need_points',
        'piecelimit','valid_type','valid_num','valid_end_at','gift_img','desc']);
        $Validate = new ValidateWxappGiftStock('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info=WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$req_data['id'],'is_del'=>1,'gift_id'=>0])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }


        if($req_data['valid_type']==1 || $req_data['valid_type']==7){
            if($req_data['valid_type']==7){
                if(!isset($req_data['valid_end_at']) || strtotime($req_data['valid_end_at'])<=0){
                    return response()->json(['code' => '001', 'msg' => '截至有效期必须为时间格式']);
                }
                $req_data['valid_end_at']=strtotime($req_data['valid_end_at']);
            }else{
                $req_data['valid_end_at']=0;

            }
            $req_data['valid_num']=0;
        }else{
            //有效期类型，1永久，2年，3季度，4月，5周，6天，7指定时间
            if(!isset($req_data['valid_num']) || $req_data['valid_num']<=0){
                return response()->json(['code' => '001', 'msg' => '请输入有效期数']);
            }else{
                if($req_data['valid_type']==2){
                    $req_data['valid_end_at']=strtotime('+'.$req_data['valid_num'].' year');
                }elseif($req_data['valid_type']==3){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']*3).' month');
                }elseif($req_data['valid_type']==4){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']).' month');
                }elseif($req_data['valid_type']==5){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']*7).' day');
                }elseif($req_data['valid_type']==6){
                    $req_data['valid_end_at']=strtotime('+'.($req_data['valid_num']).' day');
                }
            }
        }

        $data=$req_data;
        $data['desc']=isset($data['desc'])?$data['desc']:'';
        $data['current_count']=$data['total_count'];
        $data['update_account_id']=$accountinfo['id'];
        $data['update_account_real_name']=$accountinfo['real_name'];
        $data['update_at']=time();
        WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$req_data['id'],'is_del'=>1])->update($data);
        return response()->json(['code'=>'000','msg'=>'编辑成功']);
    }


    /**
     * 入库
     */
    public function dopoststockin(Request $request)
    {
        $id=intval($request->id);
        $store_id=intval($request->store_id);
        $count=intval($request->count);
        $remark=$request->remark ?? '';
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info=WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id, 'is_del'=>1])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if($info->store_id!=0){
            return response()->json(['code' => '001', 'msg' => '非财务部礼品不可操作入库']);
        }
        if($count<=0 || $count>$info->current_count){
            return response()->json(['code' => '001', 'msg' => '数量不能小于等于0或大于库存数量']);
        }
        $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $data=$info->toArray();
        $data['gift_id']=$data['id'];
        $data['store_id']=$store_id;
        $data['total_count']=$count;
        $data['current_count']=0;
        $data['create_account_id']=$accountinfo['id'];
        $data['create_account_real_name']=$accountinfo['real_name'];
        $data['update_account_id']=$accountinfo['id'];
        $data['update_account_real_name']=$accountinfo['real_name'];
        $data['create_at']=time();
        $data['update_at']=time();
        $data['remark']=$remark;
        unset($data['id']);
        unset($data['audit_status']);
        unset($data['audit_at']);
        DB::beginTransaction();
        try {
            WxappGiftStock::create($data);
            WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1])->decrement('current_count',$count);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '礼品入库操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '礼品入库操作成功']);

    }
    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $id=intval($request->id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info=WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1])->update(['is_del'=>2,'del_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }
    /**
     * 审核
     */
    public function doauditsuccess(Request $request)
    {
        $id=intval($request->id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $info=WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1,'store_id'=>$store_id])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if($info->audit_status!=1){
            return response()->json(['code' => '001', 'msg' => '已审核不可重复审核']);
        }

        DB::beginTransaction();
        try {
            WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1,'store_id'=>$store_id])->update(['audit_status'=>2,'audit_at'=>time(),'current_count'=>$info->total_count]);
            $data=[
                'cp_id'=>$cp_id,
                'gift_id'=>$info->id,
                'gift_name'=>$info->gift_name,
                'count'=>$info->total_count,
                'type'=>2,
                'store_id'=>$store_id,
                'create_account_id'=>$accountinfo['id'],
                'create_account_real_name'=>$accountinfo['real_name'],
                'update_account_id'=>$accountinfo['id'],
                'update_account_real_name'=>$accountinfo['real_name'],
                'create_at'=>time(),
                'update_at'=>time(),
                'remark'=>$info->remark,
                'start_store_id'=>0,
                'target_store_id'=>$store_id,
            ];
            WxappGiftLog::create($data);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核操作成功']);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {
        $id=intval($request->id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $info=WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1,'store_id'=>$store_id])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if($info->audit_status!=1){
            return response()->json(['code' => '001', 'msg' => '已审核不可重复审核']);
        }

        DB::beginTransaction();
        try {
            WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1,'store_id'=>$store_id])->update(['audit_status'=>3,'audit_at'=>time()]);
            WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$info->gift_id,'is_del'=>1,'store_id'=>0])->increment('current_count',$info->total_count);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '礼品取消审核操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '礼品取消审核操作成功']);
    }

    /**
     * 调拨
     */
    public function dopostallot(Request $request)
    {
        $id=intval($request->id);
        $store_id=intval($request->store_id);
        $count=intval($request->count);
        $remark=$request->remark ?? '';
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $current_store_id = intval($accountinfo['store_ids']);

        if($current_store_id==$store_id){
            return response()->json(['code' => '001', 'msg' => '目的门店不可为发起门店']);
        }
        // $current_store_id=1;

        $info=WxappGiftStock::where(['cp_id'=>$cp_id,'store_id'=>$current_store_id,'id'=>$id,'is_del'=>1])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if($info->store_id==0){
            return response()->json(['code' => '001', 'msg' => '非门店礼品不可操作调拨']);
        }

        if($info->audit_status!=2){
            return response()->json(['code' => '001', 'msg' => '非审核通过的礼品不可操作调拨']);
        }


        if($count<=0 || $count>$info->current_count){
            return response()->json(['code' => '001', 'msg' => '数量不能小于等于0或大于库存数量']);
        }
        $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $info=$info->toArray();

        $data=['cp_id'=>$cp_id];
        $data['gift_id']=$info['id'];
        $data['gift_name']=$info['gift_name'];
        $data['total_count']=$count;
        $data['store_id']=$info['store_id'];
        $data['target_store_id']=$store_id;
        $data['create_account_id']=$accountinfo['id'];
        $data['create_account_real_name']=$accountinfo['real_name'];
        $data['update_account_id']=$accountinfo['id'];
        $data['update_account_real_name']=$accountinfo['real_name'];
        $data['create_at']=time();
        $data['update_at']=time();
        $data['remark']=$remark;
        DB::beginTransaction();
        try {
            WxappGiftAllot::create($data);
            WxappGiftStock::where(['cp_id'=>$cp_id,'id'=>$id,'is_del'=>1])->decrement('current_count',$count);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '礼品调拨操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '礼品调拨操作成功']);

    }

    /**
     * 下载模板
     */
    public function downdownload(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        //1永久，2年，3季度，4月，5周，6天，7指定时间
        $row = [['礼品名称', '礼品类别', '价值', '数量', '所需积分', '兑换限制次数','有效期类型','有效期数量','到期时间']];
        $options = [
            'B'=>WxappGiftCategory::where(['cp_id' => $cp_id,'is_del'=>1])->pluck('category_name')->toArray(),
            'G'=>['永久','年','季度','月','周','天','指定时间']
        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
            'C' => '25',
            'D' => '25',
            'E' => '25',
            'F' => '25',
            'G' => '25',
            'H' => '25',
            'I' => '40',
        ];
        $filename = '礼品导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }

    /**
     * 导入礼品库存
     */
    public function doimport(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            $ins_data=[];
            $return_msg=[];
            //1永久，2年，3季度，4月，5周，6天，7指定时间
            $valid_type=['永久'=>1,'年'=>2,'季度'=>3,'月'=>4,'周'=>5,'天'=>6,'指定时间'=>7];
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if(count($val)!=9){
                        return response()->json(['code' => '001', 'msg' =>'导入数据格式错误']);
                    }
                    continue;
                }
                $val[8]=Date::excelToDateTimeObject($val[8])->format('Y-m-d H:i:s');

                if(!isset($valid_type[$val[6]])){
                    return response()->json(['code' => '001', 'msg' =>'无效有效期类型']);
                }
                
                $item=[
                    'cp_id'=>$cp_id,
                    'gift_name'=>$val[0],
                    'gift_category_id'=>intval(WxappGiftCategory::where(['category_name'=>$val[1],'cp_id'=>$cp_id,'is_del'=>1])->value('id')),
                    'price'=>$val[2]*100,
                    'total_count'=>$val[3],
                    'current_count'=>$val[3],
                    'need_points'=>$val[4],
                    'piecelimit'=>$val[5],
                    'valid_type'=>$valid_type[$val[6]],
                    'valid_num'=>intval($val[7]),
                    'valid_end_at'=>strtotime($val[8]),
                    'desc'=>''
                ];

                //print_r($item);exit;

                if($item['valid_type']==1 || $item['valid_type']==7){
                    if($item['valid_type']==7){
                        if(isset($item['valid_end_at']) || strtotime($item['valid_end_at'])<=0){
                            return response()->json(['code' => '001', 'msg' => '截至有效期必须为时间格式']);
                        }
                    }else{
                        $item['valid_end_at']=0;

                    }
                    $item['valid_num']=0;
                }else{
                    //有效期类型，1永久，2年，3季度，4月，5周，6天，7指定时间
                    if(!isset($item['valid_num']) || $item['valid_num']<=0){
                        return response()->json(['code' => '001', 'msg' => '请输入有效期数']);
                    }else{
                        if($item['valid_type']==2){
                            $item['valid_end_at']=strtotime('+'.$item['valid_num'].' year');
                        }elseif($item['valid_type']==3){
                            $item['valid_end_at']=strtotime('+'.($item['valid_num']*3).' month');
                        }elseif($item['valid_type']==4){
                            $item['valid_end_at']=strtotime('+'.($item['valid_num']).' month');
                        }elseif($item['valid_type']==5){
                            $item['valid_end_at']=strtotime('+'.($item['valid_num']*7).' day');
                        }elseif($item['valid_type']==6){
                            $item['valid_end_at']=strtotime('+'.($item['valid_num']).' day');
                        }
                    }
                }

                if($item['gift_category_id']==0 ){
                    return response()->json(['code' => '001', 'msg' => '礼品类别' . $val[1].'不存在']);
                }
                if($item['valid_type']==0){
                    return response()->json(['code' => '001', 'msg' => '有效期类型' . $val[6].'错误']);

                }

                $item['create_account_id']=$accountinfo['id'];
                $item['create_account_real_name']=$accountinfo['real_name'];
                $item['update_account_id']=$accountinfo['id'];
                $item['update_account_real_name']=$accountinfo['real_name'];
                $item['create_at']=time();
                $item['update_at']=time();
                $item['audit_status']=2;
                $ins_data[]=$item;
            }

            if(count($ins_data)<=0){
                return response()->json(['code' => '001', 'msg' => '无效数据新增失败']);
            }
            DB::beginTransaction();
            try {
                WxappGiftStock::insert($ins_data);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '礼品导入失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '礼品导入成功','data'=>['return_msg'=>$return_msg]]);

        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在']);
        }
    }

}
